﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogicLayer;
using DataAccessLayer;
using PurchaseOrderExtra;

namespace PresentationLayer
{
    public partial class SelectItemsForPurchasing : System.Web.UI.Page
    {
        SelectItemsForPurchasingControl control;
        User user;
        int categoryId;
        string categoryIdString;
        string lowStockCheck;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region Check if user exists and has permission to view this page
                if (Session["UserLoggedIn"] != null)
                {
                    List<string> list = Session["UserLoggedIn"] as List<string>;
                    if (list[0].Equals("validuser"))
                    {
                        int roleId = Convert.ToInt32(list[6]);
                        if (roleId != 5)
                        {
                            Response.Redirect("/AccessDenied.aspx");
                        }
                    }
                    else
                    {
                        Response.Redirect("/Login.aspx");
                    }
                }
                else
                {
                    Response.Redirect("/Login.aspx");
                }
                #endregion

                control = new SelectItemsForPurchasingControl();

                List<string> userList = Session["UserLoggedIn"] as List<string>;
                string username = userList[3];
                user = control.GetUserByUsername(username);

                if (!IsPostBack)
                {
                    lblMessage.Text = "";
                    categoryId = 0;
                    categoryIdString = categoryId.ToString();
                    lowStockCheck = "false";
                    List<string> displayList = new List<string>();
                    displayList.Add(categoryIdString);
                    displayList.Add(lowStockCheck);
                    ViewState["LowStockCheck"] = displayList;

                    // Populate Category dropdownist
                    PopulateCategory();
                    PopulateAllStationeryGV();
                    gvStationery.PageIndex = 0;         // Reset girdview to display first page
                    gvStationery.DataBind();
                }
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            try
            {
                gvStationery.DataSource = null;
                gvStationery.DataBind();

                List<string> displayList = new List<string>();
                categoryIdString = ddlCategory.SelectedValue;
                categoryId = Convert.ToInt32(categoryIdString);
                if (categoryId == 0)
                {
                    if (cboLowStock.Checked)
                    {
                        lowStockCheck = "true";
                        displayList.Add(categoryIdString);
                        displayList.Add(lowStockCheck);
                        ViewState["LowStockCheck"] = displayList;
                        lblMessage.Text = "";
                        PopulateAllLowStockStationeryGV();
                        gvStationery.PageIndex = 0;         // Reset girdview to display first page
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                    else
                    {
                        lowStockCheck = "false";
                        displayList.Add(categoryIdString);
                        displayList.Add(lowStockCheck);
                        ViewState["LowStockCheck"] = displayList;
                        lblMessage.Text = "";
                        PopulateAllStationeryGV();
                        gvStationery.PageIndex = 0;         // Reset girdview to display first page
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                }
                else
                {
                    if (cboLowStock.Checked)
                    {
                        lowStockCheck = "true";
                        displayList.Add(categoryIdString);
                        displayList.Add(lowStockCheck);
                        ViewState["LowStockCheck"] = displayList;
                        lblMessage.Text = "";
                        PopulateLowStockStationeryByCategoryGV();
                        gvStationery.PageIndex = 0;         // Reset girdview to display first page
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                    else
                    {
                        lowStockCheck = "false";
                        displayList.Add(categoryIdString);
                        displayList.Add(lowStockCheck);
                        ViewState["LowStockCheck"] = displayList;
                        lblMessage.Text = "";
                        PopulateStationeryByCategoryGV(categoryId);
                        gvStationery.PageIndex = 0;         // Reset girdview to display first page
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnSupplierDetail_Click(object sender, EventArgs e)
        {
            try
            {
                lblMessage.Text = "";
                GridViewRow clickedRow = ((Button)sender).NamingContainer as GridViewRow;
                Label lblItemCode = (Label)clickedRow.FindControl("lblItemCode");
                string itemCode = lblItemCode.Text;
                PopulateSupplierDetailGV(itemCode);
            }
            catch (Exception ex)
            {
            }
        }

        protected void btnAddToPO_Click(object sender, EventArgs e)
        {
            try
            {
                // Save to TempPOItem table in database
                GridViewRow clickedRow = ((Button)sender).NamingContainer as GridViewRow;
                Label lblItemCode = (Label)clickedRow.FindControl("lblItemCodeGVSup");
                string itemCode = lblItemCode.Text;
                Label lblSupplierId = (Label)clickedRow.FindControl("lblSupplierIdGVSup");
                string supplierId = lblSupplierId.Text;
                TempPOItem newTempPOItem = new TempPOItem();
                newTempPOItem.ItemCode = itemCode;
                newTempPOItem.Quantity = 1;
                newTempPOItem.SupplierID = supplierId;
                newTempPOItem.ClerkID = control.GetEmployeeByUserId(user.UserID).EmployeeID;
                newTempPOItem.Date = DateTime.Now;
                newTempPOItem.Status = "Pending";

                // Check if to update or create tempPOItem
                control.SaveTempPOItem(newTempPOItem);

                Label lblItemNamegv = (Label)clickedRow.FindControl("lblItemNameGVSup");
                string itemName = lblItemNamegv.Text;
                Label lblSupplierName = (Label)clickedRow.FindControl("lblSupplierNameGVSup");
                string supplierName = lblSupplierName.Text;
                lblMessage.Text = itemName + " from " + supplierName + " has been added to the Purchase Order Form";
            }
            catch (Exception ex)
            {
            }
        }

        #region Populate Control Information
        private void PopulateCategory()
        {
            ddlCategory.DataSource = control.DisplayAllCategory();
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataValueField = "CategoryID";
            ddlCategory.DataBind();
        }

        private void PopulateAllStationeryGV()
        {
            List<StationeryDisplay> list = control.DisplayAllStationery();
            if (list.Count <= 0)
            {
                lblMessage.Text = "There is no item in the store";
            }
            gvStationery.DataSource = list;
            //gvStationery.DataBind();
        }

        private void PopulateStationeryByCategoryGV(int categoryId)
        {
            List<StationeryDisplay> list = control.DisplayStationeryByCategory(categoryId);
            if (list.Count <= 0)
            {
                lblMessage.Text = "There is no item in this category";
            }
            gvStationery.DataSource = list;
            //gvStationery.DataBind();
        }

        private void PopulateAllLowStockStationeryGV()
        {
            List<StationeryDisplay> list = control.DisplayAllLowStockStationery();
            if (list.Count <= 0)
            {
                lblMessage.Text = "No item is below reorder level";
            }
            gvStationery.DataSource = list;
            //gvStationery.DataBind();
        }

        private void PopulateLowStockStationeryByCategoryGV()
        {
            List<string> displayList = ViewState["LowStockCheck"] as List<string>;
            categoryId = Convert.ToInt32(displayList[0]);
            List<StationeryDisplay> list = control.DisplayLowStockStationeryByCategory(categoryId);
            if (list.Count <= 0)
            {
                lblMessage.Text = "No item in this category is below reorder level";
            }
            gvStationery.DataSource = list;
            //gvStationery.DataBind();
        }

        private void PopulateSupplierDetailGV(string itemCode)
        {
            List<SupplierDetailDisplay> list = control.DisplaySupplierDetail(itemCode);
            lblItemName.Text = "Supplier Detail for Selected Item: " + list[0].ItemName;
            gvSupplier.DataSource = list;
            gvSupplier.DataBind();
        }

        private void PopulateEmptySupplierDetailGV()
        {
            lblItemName.Text = "";
            List<SupplierDetailDisplay> list = new List<SupplierDetailDisplay>();
            gvSupplier.DataSource = list;
            gvSupplier.DataBind();
        }
        #endregion

        #region GridView Function
        protected void gvStationery_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                gvStationery.PageIndex = e.NewPageIndex;
                gvStationery.EditIndex = -1;
                gvStationery.SelectedIndex = -1;
            }
            catch (Exception ex)
            {
            }
        }

        protected void gvStationery_PageIndexChanged(object sender, EventArgs e)
        {
            try
            {
                List<string> displayList = ViewState["LowStockCheck"] as List<string>;
                categoryId = Convert.ToInt32(displayList[0]);
                lowStockCheck = displayList[1];
                if (categoryId == 0)
                {
                    if (lowStockCheck.Equals("true"))
                    {
                        lblMessage.Text = "";
                        PopulateAllLowStockStationeryGV();
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                    else
                    {
                        lblMessage.Text = "";
                        PopulateAllStationeryGV();
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                }
                else
                {
                    if (lowStockCheck.Equals("true"))
                    {
                        lblMessage.Text = "";
                        PopulateLowStockStationeryByCategoryGV();
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                    else
                    {
                        lblMessage.Text = "";
                        PopulateStationeryByCategoryGV(categoryId);
                        gvStationery.DataBind();
                        PopulateEmptySupplierDetailGV();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        #endregion

        protected void btnRaisePO_Click(object sender, EventArgs e)
        {
            try
            {
                string redirectURL = control.RedirectToRaisePurchaseOrder();
                Response.Redirect(redirectURL);
            }
            catch (Exception ex)
            {
            }
        }

    }
}